<template>
    <div class="register-container">
      <el-card class="register-card">
        <template #header>
          <div class="card-header">
            <h2>DheeShop 管理员注册</h2>
          </div>
        </template>
  
        <el-form
            ref="registerFormRef"
            :model="registerForm"
            :rules="rules"
            label-width="80px"
            @submit.prevent="handleRegister"
        >
          <el-form-item label="用户名" prop="adminName">
            <el-input
                v-model="registerForm.adminName"
                placeholder="请输入管理员用户名"
                prefix-icon="User"
                clearable
            />
          </el-form-item>
  
          <el-form-item label="密码" prop="adminPass">
            <el-input
                v-model="registerForm.adminPass"
                type="password"
                placeholder="请输入密码"
                prefix-icon="Lock"
                show-password
                clearable
            />
          </el-form-item>
  
          <el-form-item label="确认密码" prop="confirmPass">
            <el-input
                v-model="registerForm.confirmPass"
                type="password"
                placeholder="请再次输入密码"
                prefix-icon="Lock"
                show-password
                clearable
                @keyup.enter="handleRegister"
            />
          </el-form-item>
  
          <el-form-item>
            <el-button
                type="primary"
                :loading="loading"
                @click="handleRegister"
                style="width: 100%"
            >
              {{ loading ? '注册中...' : '注册' }}
            </el-button>
          </el-form-item>
  
          <el-form-item class="login-form-item">
            <div class="login-link">
              <el-link type="primary" @click="handleBackToLogin">已有账号？立即登录</el-link>
            </div>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </template>
  
  <script>
  import { ref, reactive } from 'vue'
  import { ElMessage } from 'element-plus'
  import request from '../../util/request.js'
  import router from '@/router/index.js'
  
  export default {
    name: 'AdminRegister',
    setup() {
      const registerFormRef = ref()
      const loading = ref(false)

      // 注册表单数据
      const registerForm = reactive({
        adminName: '',
        adminPass: '',
        confirmPass: ''
      })

      // 自定义验证规则 - 确认密码
      const validateConfirmPass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'))
        } else if (value !== registerForm.adminPass) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      }

      // 表单验证规则
      const rules = {
        adminName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
        ],
        adminPass: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        confirmPass: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: validateConfirmPass, trigger: 'blur' }
        ]
      }

      // 处理注册
      const handleRegister = async () => {
        if (!registerFormRef.value) return

        try {
          // 验证表单
          await registerFormRef.value.validate()

          loading.value = true

          // 调用后端注册接口
          const response = await request.post('/admin/register', {
            adminName: registerForm.adminName,
            adminPass: registerForm.adminPass
          })

          // 检查响应状态
          if (response.data && (response.data.code === 1 )) {
            ElMessage.success('注册成功！请登录')

            // 清空表单
            registerForm.adminName = ''
            registerForm.adminPass = ''
            registerForm.confirmPass = ''

            router.push('/admin/login')
            console.log('注册成功')

          } else {
            const errorMsg = response.data?.msg || '注册失败'
            ElMessage.error(errorMsg)
          }

        } catch (error) {
          if (error.response) {
            const errorData = error.response.data
            if (errorData && errorData.msg) {
              ElMessage.error(errorData.msg)   // 显示错误信息
            }
          }
          }finally {
          loading.value = false
        }
      }

      // 返回登录页面
      const handleBackToLogin = () => {
        console.log('返回登录页面')
        router.push('/admin/login')
      }

      return {
        registerFormRef,
        registerForm,
        rules,
        loading,
        handleRegister,
        handleBackToLogin
      }
    }
  }
  </script>
  
  <style scoped>
  .register-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  }
  
  .register-card {
    width: 400px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    border-radius: 12px;
  }
  
  .card-header {
    text-align: center;
  }
  
  .card-header h2 {
    margin: 0;
    color: #409eff;
    font-weight: 600;
  }
  
  .login-form-item {
    margin-bottom: 0;
  }
  
  .login-link {
    text-align: center;
    width: 100%;
  }
  
  /* 优化样式 */
  :deep(.el-form-item__label) {
    font-weight: 500;
  }
  
  :deep(.el-input__inner) {
    border-radius: 6px;
  }
  
  :deep(.el-button) {
    border-radius: 6px;
    font-weight: 500;
  }
  </style>
  